<template>
  <el-form
    ref="loginForm"
    class="login-form"
    style="width: 341px"
    status-icon
    :rules="loginRules"
    :model="loginForm"
    label-width="0"
  >
    <el-form-item prop="username">
      <el-input
        v-model="loginForm.username"
        size="small"
        auto-complete="off"
        placeholder="请输入用户名"
        @keyup.enter.native="handleLogin"
      >
        <i slot="prefix" class="icon-yonghu" />
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        size="small"
        :type="passwordType"
        auto-complete="off"
        placeholder="请输入密码"
        @keyup.enter.native="handleLogin"
      >
        <i
          slot="suffix"
          class="el-icon-view el-input__icon"
          @click="showPassword"
        />
        <i slot="prefix" class="icon-mima" />
      </el-input>
    </el-form-item>
    <el-form-item v-if="website.validateCode && !this.captchaType" prop="params.code">
      <el-row :span="24">
        <el-col :span="16">
          <el-input
            v-model="loginForm.params.code"
            size="small"
            :maxlength="code.len"
            auto-complete="off"
            placeholder="请输入验证码"
            @keyup.enter.native="handleLogin"
          >
            <i slot="prefix" class="icon-yanzhengma" />
          </el-input>
        </el-col>
        <el-col :span="8">
          <div class="login-code">
            <img
              :src="code.src"
              class="login-code-img"
              @click="refreshCode"
            >
          </div>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <div style="display: flex">
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;width: 100%;">记住密码</el-checkbox>
        <a
          href="#"
          style="display: inline-block;color: rgb(24, 144, 255); font-size: 13px;text-align: right;width: 100%;"
          @click.stop="captchaType=!captchaType;loginForm.params.captchaType=captchaType?'SLIDER':'graph';loginForm.captchaTitle=captchaType?'切换图形验证码模式':'切换滑块验证码模式'"
        >{{
          loginForm.captchaTitle
        }}</a>
      </div>
      <div v-if="!tencentCaptchaBoolean">
        <Verify
          ref="verify"
          :mode="'pop'"
          :captcha-type="'blockPuzzle'"
          :img-size="{ width: '330px', height: '155px' }"
          @success="capctchaCheckSuccess"
        />
      </div>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        class="login-submit"
        @click.native.prevent="handleLogin"
      >登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import Cookies from 'js-cookie'
import Verify from '@/components/Verifition/Verify'
import { hideFullScreenLoading, showFullScreenLoading } from '@/utils/loadIng'
// import SocialSignin from '@/views/login/components/SocialSignin.vue'

import { mapGetters } from 'vuex'

export default {
  name: 'Userlogin',
  components: { Verify },
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        params: {
          code: '', // 验证码val
          randomStr: '', // 验证码key
          captchaType: 'graph' // 滑块:SLIDER  图形:graph
        },
        rememberMe: false,
        captchaTitle: '切换滑块验证码模式'
      },
      code: {
        src: '/sysLogin/captcha',
        value: '',
        len: 4,
        type: 'image'
      },
      loginRules: {
        username: [
          this.formRules.required('请输入用户名'),
          this.formRules.letterCheck()
        ],
        password: [
          this.formRules.required('请输入密码'),
          this.formRules.len(6, 12)
        ],
        'params.code': [this.formRules.required('请输入验证码')]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      // 是否使用腾讯验证码或安吉吉行为验证码   true 腾讯  false ajj
      tencentCaptchaBoolean: false,
      // 验证码类型 滑块 true  图形
      captchaType: false
    }
  },
  // 计算属性 将vuex website变量共享出来
  computed: {
    ...mapGetters(['website'])
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // 刷新验证码
    if (this.website.validateCode) {
      this.refreshCode()
    }
    this.getCookie()
  },
  methods: {
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '')
    },
    refreshCode() {
      this.loginForm.params.code = ''
      this.loginForm.params.randomStr = this.randomLenNum(this.code.len, true)
      // 请求验证码地址
      this.code.src = `${window.location.origin}${process.env.VUE_APP_BASE_API}/sysLogin/captcha?randomStr=${this.loginForm.params.randomStr}`
    },
    tencentCaptcha() {
      const captchaId = '2060673535' // 腾讯滑块验证码appid
      // 生成一个滑块验证码对象
      const _this = this// 此处处理是因为调用滑块验证码校验方法失效
      // eslint-disable-next-line no-undef
      var captcha = new TencentCaptcha(captchaId,
        function(res) {
          // 后台校验
          _this.handleLoginMe(res)// 图形验证码校验
        })
      // 滑块显示
      captcha.show()
    },
    handleLoginMe(res) {
      if (res.ret === 2) {
        this.msgError('滑块验证码关闭,验证取消。')
        return
      }
      // 后端校验逻辑
      this.loginForm.params.randStr = res.randstr
      this.loginForm.params.token = res.ticket
      // 密码加密
      // encrypt(this.loginForm.password)
      this.loading = true
      // 记住我功能
      if (this.loginForm.rememberMe) {
        console.log(this.loginForm.rememberMe)
        Cookies.set('username', this.loginForm.username, { expires: 30 })
        Cookies.set('password', this.loginForm.password, { expires: 30 })
        Cookies.set('remember-me', this.loginForm.rememberMe, { expires: 30 })
      } else {
        Cookies.remove('username')
        Cookies.remove('password')
        Cookies.remove('remember-me')
      }
      showFullScreenLoading('#login')
      // 开始登陆请求
      this.$store.dispatch('user/login', this.loginForm).then(() => {
        hideFullScreenLoading()
        this.$router.push({ path: this.redirect || '/', query: this.otherQuery }).catch(() => {
        })
      }).catch(() => {
        this.loading = false
        hideFullScreenLoading()
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const rememberMe = Cookies.get('remember-me')
      this.loginForm.username = username === undefined ? this.loginForm.username : username
      this.loginForm.password = password === undefined ? this.loginForm.password : password
      this.loginForm.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe)
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    /**
     * 行为验证码登陆
     * @param params
     */
    capctchaCheckSuccess(params) {
      // 添加code
      this.loginForm.params.code = params.captchaVerification
      this.loading = true
      // 记住我功能
      if (this.loginForm.rememberMe) {
        console.log(this.loginForm.rememberMe)
        Cookies.set('username', this.loginForm.username, { expires: 30 })
        Cookies.set('password', this.loginForm.password, { expires: 30 })
        Cookies.set('remember-me', this.loginForm.rememberMe, { expires: 30 })
      } else {
        Cookies.remove('username')
        Cookies.remove('password')
        Cookies.remove('remember-me')
      }
      showFullScreenLoading('#login')
      // 开始登陆请求
      this.$store.dispatch('user/login', this.loginForm).then(() => {
        hideFullScreenLoading()
        this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
      }).catch((error) => {
        console.log(error)
        this.loading = false
        hideFullScreenLoading()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 密码加密
          // encrypt(this.loginForm.password)
          if (this.website.validateCode) {
            if (this.captchaType) {
              // 滑块验证码     默认验证码腾讯的
              if (this.tencentCaptchaBoolean) {
                // 腾讯验证码开启
                this.tencentCaptcha()
              } else {
                // 行为验证码开启
                this.$refs.verify.show()
              }
            } else {
              // 图形验证码
              this.loading = true
              // 记住我功能
              if (this.loginForm.rememberMe) {
                console.log(this.loginForm.rememberMe)
                Cookies.set('username', this.loginForm.username, { expires: 30 })
                Cookies.set('password', this.loginForm.password, { expires: 30 })
                Cookies.set('remember-me', this.loginForm.rememberMe, { expires: 30 })
              } else {
                Cookies.remove('username')
                Cookies.remove('password')
                Cookies.remove('remember-me')
              }
              showFullScreenLoading('#login')
              // 开始登陆请求
              this.$store.dispatch('user/login', this.loginForm).then(() => {
                hideFullScreenLoading()
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery }).catch(() => {
                })
              }).catch(() => {
                this.loading = false
                hideFullScreenLoading()
              })
            }
          }
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}

</script>

<style scoped>
</style>
